package com.itheima.leyou.queue;

import com.alibaba.fastjson.JSONObject;
import com.itheima.leyou.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class OrderQueue {

    @Resource
    OrderService orderService;

    @RabbitListener(queues = "order_queue")
    public void getOrderQueue(String msg){
        //1、接收消息
        System.out.println("order_queue接收消息："+msg);

        //2、调用insertOrder方法
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> orderInfo = JSONObject.parseObject(msg, Map.class);
        try {
            resultMap = orderService.insertOrder(orderInfo);

            //3、如果调用失败，输出信息
            if (!(Boolean) resultMap.get("result")){
                System.out.println("order_queue消息处理失败："+resultMap.get("msg"));
            }
        }catch (Exception e){
            System.out.println("order_queue消息处理失败："+e.getMessage());
        }

        //4、调用成功，输出信息
        System.out.println("order_queue消息处理成功："+resultMap);
    }


    @RabbitListener(queues = "order_status_queue")
    public void updateOrderStatus(String msg){
        //1、接收到消息并输出
        System.out.println("order_status_queue接收消息："+msg);

        //2、调用orderService的更新订单状态方法
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> orderInfo = JSONObject.parseObject(msg, Map.class);

        try {
            String order_id = orderInfo.get("order_id").toString();
            String sku_id = orderInfo.get("sku_id").toString();
            resultMap = orderService.updateOrderStatus(order_id, sku_id);

            //3、如果失败则输入失败消息
            if (!(Boolean) resultMap.get("result")){
                System.out.println("order_status_queue消息处理失败："+resultMap.get("msg"));
            }
        }catch (Exception e){
            System.out.println("order_status_queue消息处理失败："+e.getMessage());
        }

        //4、调用成功，输出信息
        System.out.println("order_status_queue消息处理成功："+resultMap);
    }
}
